import Taro from '@tarojs/taro';
import {Image, View, Swiper, SwiperItem} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {actionCreator} from "../../store/actions";
import './home.scss';
import Ai from "../../asset/images/ai.png";
import AiIn from "../../asset/images/ai_in.png";
import Can from "../../asset/images/can.png";
import CanIn from "../../asset/images/can_in.png";
import Xin from "../../asset/images/xin.png";
import XinIn from "../../asset/images/xin_in.png";
import Logo from "../../asset/images/logo.png";
import Banner1 from "../../asset/images/banner1.png";
import Banner2 from "../../asset/images/banner2.png";
import Banner3 from "../../asset/images/banner3.png";
import {reLogin, request, unite} from "../../utils";
import QQMapWX from "../../utils/qqmap-wx-jssdk";
import UnionidModal from "../../components/unionid-modal/unionidModal";
import PhoneModal from "../../components/phone-modal/phoneModal";
import none from "../../asset/images/none.png";
import newPeopleBg from "../../asset/images/new_people_bg.png";
import diBg from "../../asset/images/di_bg.png";
import Close from "../../asset/images/close1.png";

class Home extends Taro.Component{
    config = {
        navigationBarTitleText: '酷生活',
        navigationBarBackgroundColor: '#ffffff',
        enablePullDownRefresh: true
    };
    state = {
        page: 1, //当前页数
        unionId: false, //授权弹窗
        phoneId: 1, //授权弹窗 手机号
        isTypeNext: false, //刚进入封面页面
        homeData: [], //动态列表
        isBanner: false, //判断是否第一次进入
        trainData: [], //课程列表
        typeAreaId: 1,
        regionStatusNext: -1,
        newPeopleStatus: false, //新人优惠券弹窗
        couponsData: [], //获取新人优惠券列表
    };

    temp = {
        isRefreshing: false, // 防止重复刷新
        isLoading: false,  //防止多次上拉刷新加载
        onDisable: false,
    };

    //监听程序初始化，初始化完成时触发（全局只触发一次），在此生命周期中通
    componentWillMount() {
        Taro.hideTabBar();
        Taro.setNavigationBarTitle({
            title: '动态镜子'
        });
        wx.setNavigationBarColor({
            frontColor: '#000000', // 必写项
            backgroundColor: '#FFFFFF', // 必写项
        })
    };
    componentDidShow(){
        const {backPage, getbackPage, userToken} = this.props;
        if (backPage) {
            this.setState({
                page: 1,
            }, () => {
                if (userToken) {
                    this.init();  // 判断地理位置是否授权
                } else {
                    this.getLogin(); //获取登陆
                }
            });
        }
        setTimeout(() => {
            getbackPage('');  //发布时清除状态
        }, 500);
    };
    componentDidMount() {
        const {userToken} = this.props;
        this.setState({
            page: 1,
        }, () => {
            if (userToken) {
                this.init();  // 判断地理位置是否授权
            } else {
                this.getLogin(); //获取登陆
            }
        });
    };

    //开启APP
    openApp = () => {
        const params = {
            url: '/wx/firstPage/change/loginState',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                this.setState({
                    isBanner: false,
                }, () => {
                    this.getLogin();
                });
            }
        });
    };

    //获取登陆
    getLogin = () => {
        const {setPeople,setMobileFlag, setExistUser} = this.props;
        reLogin().then((res) => {
            if (res.data) {
                //判断是否第一次进入
                setPeople(res.data.newUser == 'Y' ? true: false); //判断是否领取新人优惠券
                if (res.data.firstLogin == 'Y') {
                    this.setState({
                        isTypeNext: true,
                        isBanner: true,
                    })
                } else {
                    setMobileFlag(res.data.mobileFlag); //存储判断是否授权手机号 0未授权 1授权
                    setExistUser(res.data.getUserInfo == 'N' ? 0 : 1); //存储判断是否授权用户信息 0未授权 1授权
                    if (res.data.getUserInfo == 'N') {
                        this.setState({
                            unionId: true,
                            isTypeNext: true,
                            phoneId: res.data.mobileFlag, // 0未授权手机号
                        })
                    } else{
                        this.setState({
                            phoneId: res.data.mobileFlag, // 0未授权手机号
                        }, () => {
                            this.init();
                        });
                    }
                }
            }
        })
    };

    // 判断地理位置是否授权
    init = () => {
        const {map, peopleStatus} = this.props;
        this.setState({
            newPeopleStatus:  peopleStatus, //新人优惠券领取弹窗
        }, () => {
            if (peopleStatus) {
                //获取新人优惠券列表
                request({ url: '/wx/coupon/listNewUserCoupons', data:{}}).then(res => {
                    if (res && res.data) {
                        this.setState({
                            couponsData: res.data
                        });
                    }
                });
                //默认获取新人优惠券
                this.receivePeople();
            }
        });
        // 判断地理位置是否授权
        if(!(map && map.latitude && map.longitude)) {
            this.onReady(); //进行授权经纬度
        } else {
            this.getCond(); //获取列表
        }
    };

    //进行授权经纬度
    onReady = () => {
        Taro.getSetting().then((res) => {
            if (res.authSetting['scope.userLocation'] !== undefined && res.authSetting['scope.userLocation'] === false) {//非初始化进入该页面,且未授权
                Taro.showModal({
                    title: "是否授权当前位置",
                    content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
                    success: (data) => {
                        if (data.cancel) {
                            //授权成功后执行
                            if (this.temp.isRefreshing) {
                                Taro.stopPullDownRefresh(); //停止当前页面下拉刷新
                                this.temp.isRefreshing = false;
                            }
                        } else if (data.confirm) {
                            Taro.openSetting({
                                success: (datas) => {
                                    console.log(datas + 'datas');
                                    if (datas.authSetting["scope.userLocation"]) {
                                        unite.showToast("授权成功", 'success', 5000).then(() => {
                                            // 授权成功，初始化数据
                                            this.getCond(); //获取列表
                                        });

                                    } else {
                                        unite.showToast("授权失败");
                                    }
                                }
                            })
                        }
                    },
                    fail: () => {
                        //授权成功后执行
                        if (this.temp.isRefreshing) {
                            Taro.stopPullDownRefresh(); //停止当前页面下拉刷新
                            this.temp.isRefreshing = false;
                        }
                    }
                })
            } else if (res.authSetting['scope.userLocation'] === undefined) {//初始化进入
                this.getLocation(); //初始化
            } else if (res.authSetting['scope.userLocation']){
                this.getLocation();
            }
        })
    };

    // 获取地理位置
    getLocation = () => {
        const {setMap} = this.props;
        // 获取地理位置  调起 this.getLocation 授权再执行下一步
        wx.getLocation({
            type: 'gcj02' //返回可以用于wx.openLocation的经纬度
        }).then(res => {
            setMap({
                latitude: res.latitude,
                longitude: res.longitude
            });
            let _this = this;
            let qqmapsdk = new QQMapWX({
                key: '5MUBZ-IK23X-BMF4X-7BTEQ-HNILT-GZBYS'
            });
            //根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
            qqmapsdk.reverseGeocoder({
                location: {
                    latitude: res.latitude, //纬度
                    longitude: res.longitude //经度
                },
                success: (addressRes) => {
                    const {getAdcodeCode, getAdcodeName, getnOneAdcodeCode, getOneAdcodeName} = this.props;
                    let code = addressRes.result.ad_info.adcode;
                    getAdcodeCode(code);
                    getnOneAdcodeCode(code);
                    getAdcodeName(addressRes.result.address_component.city);
                    getOneAdcodeName(addressRes.result.address_component.city);
                    // this.temp.name = addressRes.result.address;
                    _this.setState({
                        // typeArea: addressRes.result.address,
                        // typeAreaNameBei: addressRes.result.ad_info.district,
                        // AreaName: addressRes.result.address_component.city,
                    }, () => {
                        _this.getCond(code); //获取列表
                    })
                }
            });
            // qqmapsdk.getDistrictByCityId({
            //     id: 350100,
            //     success: function (ret) {
            //         console.log(JSON.stringify(ret) + 'retaaaaaaaaaaaaaaaaaaaaaaaaaaa');
            //     }
            // });

        }).catch(() => {
            unite.showToast("授权失败, 重新为您获取位置,或重启小程序");
            this.getLocation();
        })
    };

    //获取列表
    getCond = (code) => {
        // unite.showToast(code);
        const {adcode, typeDatas, getClassDate, getRegionId, areaIds, adcodeCode} = this.props;
        Taro.showTabBar();
        Taro.setNavigationBarTitle({
            title: '酷生活'
        });
        Taro.setNavigationBarColor({
            frontColor: '#000000', // 必写项
            backgroundColor: '#ffffff', // 必写项
        });
        const params = {
            url: '/wx/firstPage/getConditionInit',
            data:{
                adcode: areaIds || code || adcode || adcodeCode
            }
        };
        request(params).then(res => {
            Taro.stopPullDownRefresh(); //停止当前页面下拉刷新
            if (res) {
                if(res.code == 200) {
                    typeDatas(res.data); //存储条件
                    getClassDate(res.data.weekDays[0].classDate); //默认获取时间存储
                    getRegionId(res.data.regions[0].parentRegionId); //记住省区域id
                    this.setState({
                        typeAreaId: res.data.regions[0].parentRegionId, //搜索默认区域id
                    })
                }
            }
        });

        //获取今日推荐
        request({ url: '/momments/today/recommend', data:{}}).then(res => {
            if (res && res.data) {
                var datas = [];
                res.data.forEach((item) => {
                    datas.push(item);
                });
                this.setState({
                    trainData: datas
                });
            }
        });

        this.setState({
            isTypeNext: true,
        }, () => {
        //    加载完毕  请求接口
            this.myList();
        })
    };

    //请求动态列表
    myList = () => {
        const {page} = this.state;
        this.temp.isLoading = true;
        const params = {
            url: '/momments/public',
            data:{
                pageNo: page,
                pageSize: 10,
            }
        };
        request(params).then(res => {
            this.temp.isLoading = false; //防止多次上拉加载
            if (res) {
                if(res.code == 200){
                    this.setState((prevState)=>({
                        homeData: page === 1 ? res.data : prevState.homeData.concat(res.data),
                    }));
                    //判断是否为最后一页
                    if (res.data.length < 10) {
                        this.temp.isLoading = true; //
                    }
                }
            }
        })
    };

    //授权
    unGetUserInfo = (is) => {
        const {setExistUser} = this.props;
        if (is) {
            setExistUser(1);
        }
        this.setState({
            unionId: false, //关闭 nu ni id 弹窗
        });
        this.init();  // 判断地理位置是否授权
    };

    //授权手机号
    unGetPhone = () => {
        this.setState({
            phoneId: 1, //关闭弹窗
        });
    };

    //跳转详情页
    skipDetail = (id, dtId) => {
        //id 课程id dtId 动态id
        Taro.navigateTo({
            url: `./detail/detail?id=${id}&dtId=${dtId}`
        })
    };

    //跳转课程详情
    skipCourseDetail = (classId, dispatchId, reservedStatus) => {
        Taro.navigateTo({
            url: '../index/course-detail/courseDetail?classId=' + classId + '&dispatchId=' + dispatchId + '&reservedStatus=' + reservedStatus,
        })
    };

    //跳转课程列表
    skipList = () => {
        const {typeAreaId, regionStatusNext} = this.state;
        Taro.navigateTo({
            url: `../index/course-list/courseList?typeAreaId=${typeAreaId}&moneyId=-1&regionStatusNext=${regionStatusNext}`
        })
    };

    //动态点赞 取消赞
    isShouc = (isLike, dtId, index, e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        //   isLike 0未点赞，1已点赞
        if(this.temp.onDisable) return;
        this.temp.onDisable = true;
        const params = {
            url: '/momments/likeOpt',
            data:{
                opt:  isLike == 0 ? 1 : 0,
                type: 0,
                uid: dtId,
            }
        };
        request(params, '', '', '', false).then(res => {
            this.temp.onDisable = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    this.setState((prevState) => {
                        if (isLike == 0) { //未点赞
                            prevState.homeData[index].likeCount = Number(prevState.homeData[index].likeCount) + 1;
                            prevState.homeData[index].isLike = 1;
                        } else { //已点赞
                            prevState.homeData[index].likeCount = Number(prevState.homeData[index].likeCount) - 1;
                            prevState.homeData[index].isLike = 0;
                        }
                        return{
                            homeData: prevState.homeData
                        }
                    })
                }
            }
        })
    };

    //关闭新人优惠券弹窗
    closePeople = () => {
        this.setState((pervState) =>({
            newPeopleStatus: !pervState.newPeopleStatus
        }));
    };

    //领取新人优惠券
    receivePeople = () => {
        const {setPeople} = this.props;
        const params = {
            url: '/wx/coupon/getNewUserCoupons',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200){
                    unite.showToast('领取成功');
                    setPeople(false);
                }
            }
        })
    };

    // 下拉刷新
    onPullDownRefresh = () => {
        this.setState({
            page: 1,
        }, () => {
            this.init();
        })
    };

    //底部上拉刷新加载更多
    onReachBottom() {
        if(this.temp.isLoading) return;
        this.setState((pervState) =>({
            page: pervState.page + 1
        }),() => {
            this.myList();
        })
    };

    render() {
        const {homeData, unionId, phoneId, isTypeNext, isBanner, trainData, newPeopleStatus, couponsData} = this.state;
        const {peopleStatus} = this.props;
        return (
            <View className="page">
                {/*<View className="home-top-wrap">*/}
                {/*    <View className="name">今日专属推荐</View>*/}
                {/*    {trainData && trainData.length != 0 &&(*/}
                {/*        <View className="flex-top home-list-content">*/}
                {/*            {trainData && trainData.map((item, index) => (*/}
                {/*                <View className="home-list" key={index} onClick={this.skipCourseDetail.bind(this, item.classId, item.dispatchId, item.reservedStatus)}>*/}
                {/*                    <View className="img-ck flex-center">*/}
                {/*                        <Image className="imgs-ai" src={item.collectionStatus == 0 ? Ai : AiIn} mode="aspectFit"/>*/}
                {/*                        <Image className="imgs" src={item.avatar} mode="aspectFit"/>*/}
                {/*                    </View>*/}
                {/*                    <View className="home-details">*/}
                {/*                        <View className="home-name text-overflow">{item.className}</View>*/}
                {/*                        <View className="flex-l cart-text">*/}
                {/*                            {item.star >= 1 && (*/}
                {/*                                <Image className="xin-icon" src={XinIn} mode="aspectFit"/>*/}
                {/*                            )}*/}
                {/*                            {item.star >= 2 ? (*/}
                {/*                                <Image className="xin-icon" src={XinIn} mode="aspectFit"/>*/}
                {/*                            ) : (*/}
                {/*                                <Image className="xin-icon" src={Xin} mode="aspectFit"/>*/}
                {/*                            )}*/}
                {/*                            {item.star >= 3 ? (*/}
                {/*                                <Image className="xin-icon" src={XinIn} mode="aspectFit"/>*/}
                {/*                            ) : (*/}
                {/*                                <Image className="xin-icon" src={Xin} mode="aspectFit"/>*/}
                {/*                            )}*/}
                {/*                            {item.star >= 4 ? (*/}
                {/*                                <Image className="xin-icon" src={XinIn} mode="aspectFit"/>*/}
                {/*                            ) : (*/}
                {/*                                <Image className="xin-icon" src={Xin} mode="aspectFit"/>*/}
                {/*                            )}*/}
                {/*                            {item.star >= 5 ? (*/}
                {/*                                <Image className="xin-icon" src={XinIn} mode="aspectFit"/>*/}
                {/*                            ) : (*/}
                {/*                                <Image className="xin-icon" src={Xin} mode="aspectFit"/>*/}
                {/*                            )}*/}
                {/*                            <View>{item.score}</View>*/}
                {/*                        </View>*/}
                {/*                        <View className="flex-lr detail-title">*/}
                {/*                            <View>{item.coachInfo.coachName}</View>*/}
                {/*                            <View>{item.rank}.{item.orderTotal}节</View>*/}
                {/*                        </View>*/}
                {/*                    </View>*/}
                {/*                </View>*/}
                {/*            ))}*/}
                {/*        </View>*/}
                {/*    )}*/}
                {/*    <View className="skip-btn flex-center" onClick={this.skipList}>查看更多</View>*/}
                {/*</View>*/}
                <View className="home-top-wrap">
                    {/*<View className="name">酷生活</View>*/}
                    {homeData && homeData.length != 0 &&(
                        <View className="home-list-content home-list-content-next flex-top">
                            {homeData && homeData.map((item, index) => (
                                <View className="home-list home-list-next" key={index} onClick={this.skipDetail.bind(this, item.dispatchId, item.momentId)}>
                                    <View className="img-ck flex-center">
                                        <Image className="imgs" src={item.imgs[0].imgUrl} mode="aspectFill"/>
                                    </View>
                                    <View className="home-details">
                                        <View className="home-name text-overflow-two">{item.title}</View>
                                        <View className="flex-lr detail-title">
                                            <View className="flex-l">
                                                <Image className="heads" src={item.authorAvatar}/>
                                                <View className="text-name text-overflow">{item.authorName}</View>
                                            </View>
                                            <View className="flex-r" onClick={this.isShouc.bind(this, item.isLike, item.momentId, index)}>
                                                <Image className="cans" src={item.isLike == 1 ? CanIn : Can} mode="aspectFit"/>
                                                <View>{item.likeCount}</View>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            ))}
                            {homeData && homeData.length == 0 &&(
                                <View className="none">
                                    <Image src={none}/>
                                    <View>暂无数据</View>
                                </View>
                            )}
                        </View>
                    )}
                </View>
                {unionId &&(
                    <UnionidModal onCancel={this.unGetUserInfo}/>
                )}
                {/*{phoneId == 0 &&(*/}
                {/*    <PhoneModal onCancel={this.unGetPhone}/>*/}
                {/*)}*/}
                {!isTypeNext &&(
                    <View className="index-model-next">
                        <Image className="model-next-logo" src={Logo} mode="widthFix"/>
                        <View className="text">动态镜子</View>
                        <View className="jiazai-text flex-center">
                            <View>我最酷的生活</View>
                        </View>
                    </View>
                )}
                {/*轮播图*/}
                {isBanner && (
                    <View className="member-banner">
                        <View className="banner-bd">
                            <Swiper
                                className='test-h'
                                indicatorColor='#BFBFBF'
                                indicatorActiveColor='#333333'
                                circular
                                indicatorDots
                                autoplay
                            >
                                <SwiperItem>
                                    <Image
                                        className="img"
                                        src={Banner1}
                                        mode="widthFix"
                                    />
                                </SwiperItem>
                                <SwiperItem>
                                    <Image
                                        className="img"
                                        src={Banner2}
                                        mode="widthFix"
                                    />
                                </SwiperItem>
                                <SwiperItem>
                                    <Image
                                        className="img"
                                        src={Banner3}
                                        mode="widthFix"
                                    />
                                </SwiperItem>
                            </Swiper>
                        </View>
                        <View className="banner-btn flex-center" onClick={this.openApp.bind(this)}>立刻体验</View>
                    </View>
                )}
            {/*    新人优惠券弹窗*/}
                {newPeopleStatus && (
                    <View className="model-type flex-center">
                        <View className="people-constnt-wrap">
                            <Image className="imgs-people" src={newPeopleBg} mode="aspectFit"/>
                            <Image className="imgs-close" onClick={this.closePeople} src={Close} mode="aspectFit"/>
                            <View className="people-content">
                                <View className="content-wrap">
                                    {couponsData && couponsData.map((item, index) => (
                                        <View className="item-list" key={index}>
                                            <Image className="imgs-list" src={diBg} mode="aspectFit"/>
                                            <View className="left-titles">
                                                <View className="price">￥{item.favourableCharge}</View>
                                                <View>满{item.minCharge}可用</View>
                                            </View>
                                            <View className="left-titles-next">
                                                <View className="name">{item.clientName}</View>
                                                <View className="tiishi">有效期：{item.effectTime}{item.expireTime ? '~' + item.expireTime : item.expireTime}</View>
                                            </View>
                                        </View>
                                    ))}
                                </View>
                                <View className="btns-wrap flex-center">
                                    <View className="btns flex-center" onClick={this.closePeople}>我知道了</View>
                                    {/*{peopleStatus ? (*/}
                                    {/*    <View className="btns flex-center" onClick={this.receivePeople}>点击领取</View>*/}
                                    {/*) : (*/}
                                    {/*    <View>*/}
                                    {/*        <View className="succus-name">已成功领取</View>*/}
                                    {/*        <View className="succus-names-next">在“我的-优惠券查看”</View>*/}
                                    {/*    </View>*/}
                                    {/*)}*/}
                                </View>
                            </View>
                        </View>
                    </View>
                )}
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {userToken, map, backPage, searchTitle, areaIds, adcodeCode, adcodeName,oneAdcodeCode, oneAdcodeName, getData, peopleStatus} = state;
    return {
        userToken,
        map,
        backPage,
        searchTitle,
        areaIds,
        adcodeCode,
        adcodeName,
        oneAdcodeCode,
        oneAdcodeName,
        getData,
        peopleStatus
    }
};

const mapDispatchToProps = {
    getbackPage: actionCreator.getbackPage,
    setMap: actionCreator.setMap,
    typeDatas: actionCreator.typeData,
    getClassDate: actionCreator.getClassDate,
    getSearchTitle: actionCreator.getSearchTitle,
    getRegionId: actionCreator.getRegionId,
    getAdcodeCode: actionCreator.getAdcodeCode,
    getAdcodeName: actionCreator.getAdcodeName,
    getnOneAdcodeCode: actionCreator.getnOneAdcodeCode,
    getOneAdcodeName: actionCreator.getOneAdcodeName,
    setPeople: actionCreator.setPeople,
    setMobileFlag: actionCreator.setMobileFlag,
    setExistUser: actionCreator.setExistUser
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);
